/**
 * Created by Administrator on 2017/6/25.
 */
import React, { Component } from 'react';

export default  class StarRating extends Component {
    constructor(props) {
        super(props);
        this.state={
            "size":props.size||5,
            "score":props.score||0
        };
        this.tempScore = -1;
    }
    //获取显示的样式
    getStarClasses(){
        let starClasses = [];
        for(let i=0;i<this.state.score;i++){
            starClasses.push("star-item star-item-on");
        }
        while(starClasses.length<this.state.size){
            starClasses.push("star-item star-item-off");
        }
        return starClasses;
    }
    //处理单击设置新的状态
    handleStarClick(idx){
        this.setState({
            score:idx+1
        });
        this.tempScore = -1;
    }
    //处理鼠标悬停
    handleStarMouseHover(idx){
        if(this.tempScore === -1){
            this.tempScore = this.state.score
        }
        this.setState({
            score:idx+1
        })
    }
    //处理鼠标移出
    handleMouseOut(){
        if(this.tempScore !== -1){
            this.setState({
                score:this.tempScore
            })
            this.tempScore = -1;
        }
    }
    //清除选择
    handleClearStars(){
        this.setState({
            score:0
        })
    }

    render() {
        return (
            <span className="rating-wrap" onMouseOut = {this.handleMouseOut.bind(this)} >
        {
            this.getStarClasses().map((item, index) =>
            <span className = {item} onClick = {this.handleStarClick.bind(this, index)} onMouseOver = {this.handleStarMouseHover.bind(this, index)} key = {index} >★</span >
            )
        }
        {
                this.state.score>0?
                    <a href="#" className="star-clear" onClick={this.handleClearStars.bind(this)}>×</a>
                :""
            }

            </span>
        )
    }
}
